<?php

namespace app\admin\controller\purchase;

use app\common\model\data\Voucher;
use app\common\controller\Backend;

use app\common\model\goods\GoodsHouseStock;
use app\common\model\goods\Goods as GoodsModel;
use app\common\model\purchase\Change;
use app\common\model\purchase\ChangeGoods;
use app\common\model\purchase\EnterGoods;
use app\common\model\purchase\Goods;
use app\common\model\purchase\Retreat;
use app\common\model\supplier\Supplier;
use app\common\model\purchase\RetreatGoods;
use app\common\model\Storehouse;
use think\Db;
use think\Exception;
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
use \PhpOffice\PhpSpreadsheet\IOFactory;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Enter extends Backend
{
    
    /**
     * Enter模型对象
     * @var \app\common\model\purchase\Enter
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\purchase\Enter;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $this->handlefilter();

            $filter = json_decode($this->request->get('filter'),true);
            $op = json_decode($this->request->get('op'),true);


            if (isset($filter['goods_name']) || isset($filter['goods_number'])){
                if(isset($filter['goods_name'])){
                    $gids = Db::name('goods')->where(array('title'=>array('like','%'.trim($filter['goods_name']).'%')))->field('id')->select();
                    $ids = [];
                    foreach ($gids as $v){
                        $ids[]= $v['id'];
                    }
                    $eids = Db::name('purchase_enter_goods')->where(array('goods_id'=>array('in',$ids)))->column('purchase_enter_id');

                    $filter['id'] = $eids;
                    $op['id'] = 'in';
                    unset($filter['goods_name']);
                }
                if (isset($filter['goods_number'])){
                    $gids = Db::name('goods')->where(array('number'=>trim($filter['goods_number'])))->find();
                    $eids = Db::name('purchase_enter_goods')->where(array('goods_id'=>$gids['id']))->column('purchase_enter_id');
                    $filter['id'] = $eids;
                    $op['id'] = 'in';
                    unset($filter['goods_number']);
                }

                $this->request->get(["filter"=> json_encode($filter),'op'=>json_encode($op)]);
            }




            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['purchaseorder','supplier','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['purchaseorder','supplier','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','createtime','number','operator','company','explain','abstract','paytime','status','is_share']);
                $row->visible(['purchaseorder']);
				$row->getRelation('purchaseorder')->visible(['number']);
				$row->visible(['supplier']);
				$row->getRelation('supplier')->visible(['nickname']);
				$row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $status = $this->model->enter_status();
            foreach ($list as $k => $v){
                if($v['status'] >2 ){
                    $list[$k]['is_share'] = 1;
                }
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $status[$v['status']];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
//    public function examine($ids = null){
//
//        $status = input('status/d',0);
//        if(!$status){
//            $this->error('非法操作');
//        }
//        $row = $this->model->find($ids);
////        Db::startTrans();
////        try {
//
//            $res = $this->model->save(array('status' => $status), array('id' => $ids));
//            if ($res) {
////                if ($status == 2) {//确定出库
////                    $Slip = new Slip;
////                    $ress = $Slip->checkstatus($row['sales_slip_id']);
////                    if(!$ress){
////                        throw new Exception('异常错误');
////                    }
////                }
////                Db::commit();
//                return array(
//                    'code' => 1,
//                    'msg' => '成功'
//                );
//            }
//            $this->error('');
////            throw new Exception('错误异常');
////        }catch (\Exception $e) {
////            // 回滚事务
////            Db::rollback();
////            $this->error($e->getMessage());
////        }
//    }
    public function retreat($ids){

        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

        $row = $this->model->find($ids);
        if ($this->request->isAjax()) {

            $collectiontime = strtotime(input('collectiontime'));
//            $createtime = strtotime(input('createtime'));

            $explain = input('explain');
//            $abstract = input('abstract');

            $params = input();
            if(!isset($params['row'])){
                $this->error('未选择商品');
            }
            $sdata = $params['row'];

            $actual_cost = 0;
            foreach ($sdata as $k=> $v){
                $RetreatGoods = new RetreatGoods();
                $where = array(
                    'goods_id' => $v['goods_id'],
                    'purchase_goods_id' => $v['purchase_goods_id'],
                    'purchase_enter_id' => $ids,
                    'purchase_order_id' => $row['purchase_order_id'],
                );
                $rnum = $RetreatGoods->where(array(
                    'goods_id' => $v['goods_id'],
                    'purchase_goods_id' => $v['purchase_goods_id'],
                    'purchase_enter_goods_id' => $v['purchase_enter_goods_id'],
                    'purchase_enter_id' => $ids,
                    'purchase_order_id' => $row['purchase_order_id'],
                ))->sum('goods_num');//已经退货数量
                $EnterGoods = new EnterGoods;
                $gnum = $EnterGoods->where($where)->sum('goods_num');

                if($v['goods_num']+$rnum >$gnum){
                    $this->error('商品'.$k.'退货超量,已经退货'.$rnum);
                }
                $actual_cost = bcadd($actual_cost,$v['goods_num']*$v['ht_price'],4);
            }

            $num = Db::name('purchase_retreat')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $saledata = array(
                'number'=>'XT-T-'.date('Y-m-d').'-'.getnumber($num),
                'collectiontime'=>$collectiontime,
                'supplier_id'=>$row['supplier_id'],
                'storehouse_id'=>$row['storehouse_id'],
                'explain'=>$explain,
                'actual_cost'=>$actual_cost,
                'tax'=>$row['tax'],
//                'abstract'=>$abstract,
//                'tax'=>$row['tax'],
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'purchase_order_id' => $row['purchase_order_id'],
                'operator'=>session('admin')['nickname'],
                'purchase_enter_id' => $ids,
            );

            Db::startTrans();
            try {
                $Retreat = new Retreat;
                $Retreat->save($saledata);
                if(!$Retreat->id){
                    throw new Exception('操作失败');
                }

                $gdata = [];
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$row['storehouse_id'],
                    'bill_id'=>$Retreat->id,
                    'type'=>3,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                foreach ($sdata as $k => $v) {
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'purchase_enter_goods_id' => $v['purchase_enter_goods_id'],
                        'purchase_goods_id' => $v['purchase_goods_id'],
                        'goods_num' => $v['goods_num'],
                        'unit_price' => $v['unit_price'],
                        'ht_price' => $v['ht_price'],
                        'tax' => $v['tax'],
                        'remark' => $v['remark'],
                        'purchase_enter_id' => $ids,
                        'purchase_order_id' => $row['purchase_order_id'],
                        'purchase_retreat_id' => $Retreat->id,
                        'storehouse_id'=>$row['storehouse_id'],
//                        'purchase_enter_goods_id'=>$row['storehouse_id'],
                    );
                }
                $RetreatGoods = new RetreatGoods();
                $RetreatGoods->saveAll($gdata);

                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'添加成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }


            exit;
        }
        $glist = Db::name('purchase_enter_goods')
            ->field('sg.id,purchase_goods_id,goods_num,unit_price,tax,remark,title,place_origin,number,unit,specs,sg.goods_id,ht_price')
            ->alias('sg')
            ->where(array('purchase_enter_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();

        foreach ($glist as $k => $v){
            $RetreatGoods = new RetreatGoods();
            $where = array(
                'purchase_enter_goods_id' => $v['id'],
                'purchase_enter_id' => $ids,
                'purchase_order_id' => $row['purchase_order_id'],
            );
            $rnum = $RetreatGoods->where($where)->sum('goods_num');//已经退货数量
            $glist[$k]['rnum'] =$rnum;

            $GoodsHouseStock = new GoodsHouseStock;
            $glist[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$row['storehouse_id']);
            $glist[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);
        }
        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $this->assign('glist',$glist);
        $this->assign('row',$row);
        $arr = explode('/',$_SERVER['REQUEST_URI']);

        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    public function change($ids){

        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

        $row = $this->model->find($ids);

        if ($this->request->isAjax()) {

            $collectiontime = strtotime(input('collectiontime'));
//            $createtime = strtotime(input('createtime'));

            $explain = input('explain');
//            $abstract = input('abstract');

            $params = input();
            if(!isset($params['row'])){
                $this->error('未选择商品');
            }
            if(!isset($params['crow'])){
                $this->error('未选择换货商品');
            }
            $sdata = $params['row'];
            //检测库存
            $cdata = $params['crow'];

            foreach ($sdata as $k=> $v){
                $EnterGoods = new EnterGoods;
                $einfo = $EnterGoods->where(array('id'=>$v['goods_id']))->find();
                $sdata[$k]['goods_id'] =$einfo['goods_id'];
            }

            foreach ($sdata as $k=> $v){
                $ChangeGoods = new ChangeGoods();
                $where = array(
                    'purchase_enter_id' => $ids,
                    'goods_id' => $v['goods_id'],
                    'purchase_goods_id' => $v['purchase_goods_id'],
                    'purchase_order_id' => $row['purchase_order_id'],
                );
                $cnum = $ChangeGoods->where($where)->sum('goods_num');//已经换货数量
                $EnterGoods = new EnterGoods;
                $gnum = $EnterGoods->where($where)->sum('goods_num');
                if($v['goods_num']+$cnum >$gnum){
                    $this->error('商品'.$k.'换货超量,已经换货'.$cnum);
                }
            }
            $num = Db::name('purchase_change')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $saledata = array(
                'number'=>'XT-T-'.date('Y-m-d').'-'.getnumber($num),
                'collectiontime'=>$collectiontime,
                'supplier_id'=>$row['supplier_id'],
                'storehouse_id'=>$row['storehouse_id'],
                'explain'=>$explain,
//                'abstract'=>$abstract,
//                'tax'=>$row['tax'],
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'purchase_order_id' => $row['purchase_order_id'],
                'operator'=>session('admin')['nickname'],
                'purchase_enter_id' => $ids,

            );

            Db::startTrans();
            try {
                $Change = new Change();
                $Change->save($saledata);
                $gdata = [];

                foreach ($sdata as $k => $v) {
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'unit_price' => $v['unit_price'],
                        'ht_price' => $v['ht_price'],
                        'purchase_goods_id' => $v['purchase_goods_id'],
                        'tax' => $v['tax'],
                        'remark' => $v['remark'],
                        'purchase_enter_id' => $ids,
                        'purchase_order_id' => $row['purchase_order_id'],
                        'purchase_change_id' => $Change->id,
                    );
                }
                foreach ($cdata as $v){
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'unit_price' => $v['unit_price'],
                        'tax' => $v['tax'],
                        'remark' => $v['remark'],
                        'purchase_enter_id' => $ids,
                        'purchase_order_id' => $row['purchase_order_id'],
                        'purchase_change_id' => $Change->id,
                        'type'=>2,
                    );
                }

                $ChangeGoods = new ChangeGoods();
                $ChangeGoods->saveAll($gdata);
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'添加成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }


            exit;
        }
        $glist = Db::name('purchase_enter_goods')
            ->field('sg.id,purchase_goods_id,goods_num,unit_price,tax,remark,title,place_origin,number,unit,specs')
            ->alias('sg')
            ->where(array('purchase_enter_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();
        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $this->assign('glist',$glist);
        $this->assign('row',$row);
        $arr = explode('/',$_SERVER['REQUEST_URI']);
        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    public function detail($ids){
        $row = $this->model->find($ids);
        if ($this->request->isAjax()) {
            $params = input('row/a');
            foreach ($params as $v){
                if($v['goods_num'] <1){
                    $this->error('入库数量不能为0');
                }
                $egoods = new EnterGoods();
                $erow = $egoods->where(array('id'=>$v['goods_id']))->find();
                $ogoods = new Goods();
                $grow = $ogoods->where(array('id'=>$erow['purchase_goods_id'],'purchase_order_id'=>$erow['purchase_order_id'],'goods_id'=>$erow['goods_id']))->find();
                //已入库数量
                $egoods = new EnterGoods();
                $rnum = $egoods->where(array('goods_id'=>$erow['goods_id'],'purchase_order_id'=>$erow['purchase_order_id'],'status'=>2))->sum('goods_num');
                $orderrow = Db::name('purchase_order')->find($erow['purchase_order_id']);
                //如果采购单为已完成情况
                $suc_num = 0;
                if($orderrow['status'] == 4){
                    $order_num = Db::name('purchase_enter')->where(array('purchase_order_id'=>$orderrow['id'],'status'=>1))->count();
                    $suc_num = $order_num-1;
                }

                if($grow['goods_num']-$suc_num < $v['goods_num']+$rnum){
                    $this->error($v['goods_id'].'商品数量超过采购数量,目前已经实际入库'.$rnum.'采购数量为'.$grow['goods_num']);
                }
            }
            Db::startTrans();
            try{
                $this->model->save(array(
                    'status'=>2,
                    'allfare'=>input('allfare/d'),
                    'discount'=>input('discount'),
                    'discount_explain'=>input('discount_explain'),
                    'goods_cost'=>input('goods_cost'),
                    'actual_cost'=>input('actual_cost'),
                ),array(
                    'id'=>$ids,
                ));
                $row['allfare'] = input('allfare/d');


                $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();

                foreach ($params as $v){
                    $egoods = new EnterGoods();
                    $egoods->save(array('goods_num'=>$v['goods_num'],'status'=>2),array('id'=>$v['goods_id']));
//                    // 增加库存
                    $erow = EnterGoods::get($v['goods_id']);
                    $house = new GoodsHouseStock();

                    //数据对比
                    $goods = new Goods();
                    $ginfo = $goods->where(array('purchase_order_id'=>$erow['purchase_order_id'],'goods_id'=>$erow['goods_id']))->find();
                    //剩余可入库数量 = 采购数量-已入库数量
                    $EnterGoods = new EnterGoods;
                    $egoodcont = $EnterGoods->where(array('purchase_order_id'=>$erow['purchase_order_id'],'goods_id'=>$erow['goods_id'],'status'=>array('>',0)))->sum('goods_num');

                    if($egoodcont > $ginfo['goods_num']  ){
                        throw new Exception('商品'.$v['goods_id'].'数量超过采购数量,目前入库'.$egoodcont);
                    }else{
                        //相等的情况下 全部入库了
                        if($ginfo['goods_num'] == $egoodcont){
                            $goods = new Goods();
                            $goods->save(array('status'=>4),array('id'=>$ginfo['id']));
                        }else{
                            $goods = new Goods();
                            $goods->save(array('status'=>3),array('id'=>$ginfo['id']));
                        }
                    }

                    $res = $house->addstock($erow['goods_id'],$row['storehouse_id'],$v['goods_num'],handle_price($v['ht_price'],$v['tax']));
                    if(!$res){
                        throw new Exception('库存计算错误');
                    }
                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$erow['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();

                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$erow['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'采购入库单',
                        'source'=>2,
                        'type_id'=>$ids,
                        'enter_num'=>$v['goods_num'],
                        'before_num'=>$hgood['stock']-$v['goods_num'],
                        'now_num'=>$hgood['stock'],
                        'storehouse_id'=>$row['storehouse_id'],
                        'controller'=>'purchase/enter',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'final_cost'=>handle_price($v['ht_price'],$v['tax']), //记录的金额应该是入库的加权单价
//                        'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                        'bill_cost'=>handle_price($v['ht_price'],$v['tax'])*$v['goods_num'], //记录的金额应该是入库的采购成本
                        'balance'=>$hgood['balance'], //记录的金额当前库存总额
//                        'final_cost'=>$v['unit_price'],
                    ));

                }
                //已入库数量
                $egoods = new EnterGoods();
                $rnum = $egoods->where(array('purchase_order_id'=>$row['purchase_order_id'],'status'=>array('>',0)))->sum('goods_num');
                $ogoods = new Goods();
                $gnum = $ogoods->where(array('purchase_order_id'=>$row['purchase_order_id'],'status'=>array('>',0)))->sum('goods_num');

                if($rnum <$gnum){
                     Db::name('purchase_order')->where(array('id'=>$row['purchase_order_id']))->update(array('status'=>3));
                }else{
                     Db::name('purchase_order')->where(array('id'=>$row['purchase_order_id']))->update(array('status'=>4));
                }



                if($row['allfare'] >0) {
//                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

                    $custrow = Supplier::find(1);
                    $formcorw = Supplier::find($row['supplier_id']);
                    $ress = Db::name('analysis')->insert(array(
                        'is_income' => 2,
                        'source' => 2,
                        'cost' => $row['allfare'],
//                    'admin_id' => session('admin')['id'],
//                    'group_id' => $group['group_id'],
//                    'company' => $group['name'],
                        'admin_id' => $row['admin_id'],
                        'group_id' => $row['group_id'],
                        'company' => $row['company'],
                        'operator' => $row['operator'],
                        'source_id' => $ids,
                        'obj_id' => 1,
                        'storehouse_id' => $row['storehouse_id'],
//                    'operator' => session('admin')['nickname'],
                        'controller' => 'purchase/enter',
                        'settle_name' => $custrow['nickname'],
                        'number' => $row['number'],
                        'createtime' => time(),
                        'explain' => $formcorw['nickname'],//摘要
                    ));
                    if (!$ress) {
                        throw new Exception('数据异常');
                    }
                }
                $type = 1;
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>$type,
                    'createtime'=>time(),
                    'controller'=>'purchase/enter',
                    'source_id'=>$ids,
                    'source'=>2,
                    'remark'=>'采购入库单',
                    'number'=>$row['number'],
                ));

                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'审核成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            exit;
        }
        $list = Db::name('purchase_enter_goods')
            ->field('pg.id,g.number,title,place_origin,specs,goods_num,unit_price,tax,remark,pg.goods_id,storehouse_id,unit,ht_price')
            ->alias('pg')
            ->where(array('purchase_enter_id'=>$ids))
            ->join('goods g','pg.goods_id = g.id')
            ->select();
        foreach ($list as  $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
        }
        $Voucher = new Voucher;
        $vrow = $Voucher->where(array('source_id'=>$ids,'type'=>2))->find();

        $this->assign('vrow',$vrow);
        $this->assign('row',$row);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    public function share($ids = null){
        $row = $this->model->find($ids);
        if ($this->request->isAjax()) {
            if($row['status'] !=2){
                $this->error('状态不允许分摊');
            }
            $sharerow = Db::name('purchase_share')->where(array('purchase_enter_id'=>$ids,'status'=>1))->find();
            if($sharerow){
                $this->error('已存在分摊单据');
            }
            $com_fare = input('com_fare');
            $gdata = input('row/a');

            if($com_fare>0){
                Db::startTrans();
                try {

                    foreach ($gdata as $v){
                        if(empty($v['share_price'])){
                            throw new Exception('参数不全');
                        }
                    }

//                if($com_fare >0){
                    //分摊单据
                    $num = Db::name('purchase_share')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();

                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();

                    $cdata = array(
                        'createtime'=>time(),
                        'storehouse_id'=>$row['storehouse_id'],
                        'cost'=>$com_fare,
                        'purchase_enter_id'=>$ids,
                        'explain'=>input('explain'),
                        'number' =>'JKFY-T-'.date('Y-m-d').'-'.getnumber($num),
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                    );
                    $sid = Db::name('purchase_share')->insertGetId($cdata);
                    if(!$sid){
                        throw new Exception('数据异常');
                    }
//                }

                    foreach ($gdata as $v) {
                        $EnterGoods = new EnterGoods;
                        $row = $EnterGoods->where(array('id' => $v['goods_id']))->find();
                        if ($row) {
                            $EnterGoods = new EnterGoods;
                            $costprice = $v['share_price'] / $row['goods_num']+$row['unit_price'];

                            $EnterGoods->save(array(
                                'share_price' => $v['share_price'],
                                'cost_price' => $costprice,
                                'is_share' => 1,
                            ), array('id' => $row['id']));

                            $GoodsHouseStock = new GoodsHouseStock;
                            $groww = $GoodsHouseStock->where(array('goods_id'=>$row['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
                            if(empty($groww['stock'])){
                                throw new Exception('库存为0');
                            }
                            $balance = $groww['balance']+$v['share_price'];
                            $weighting_cost = $balance/$groww['stock'];

                            $GoodsHouseStock = new GoodsHouseStock;
                            $GoodsHouseStock->save(array(
//                            'cumulative'=>$row['goods_num']+$groww['cumulative'],
                                'weighting_cost'=>$weighting_cost,
                                'balance'=>$balance,
                            ),array('id'=>$groww['id']));


                            Db::name('bill')->insert(array(
                                'storehouse_id'=>$row['storehouse_id'],
                                'bill_id'=>$sid,
                                'type'=>13,
                                'admin_id'=>session('admin')['id'],
                                'group_id'=>$group['group_id'],
                                'createtime'=>time(),
                            ));
                            //库存变化
                            Db::name('goods_stock_log')->insert(array(
                                'goods_id'=>$row['goods_id'],
                                'createtime'=>time(),
                                'number'=>$cdata['number'],
                                'type'=>'采购入库分摊单',
                                'source'=>13,
                                'type_id'=>$sid,
                                'enter_num'=>0,
                                'before_num'=>0,
                                'now_num'=>$groww['stock'],
                                'storehouse_id'=>$row['storehouse_id'],
                                'controller'=>'purchase/share',
                                'admin_id'=>session('admin')['id'],
                                'group_id'=>$group['group_id'],
                                'company'=>$group['name'],
                                'operator'=>session('admin')['nickname'],
                                'final_cost'=>$balance/$groww['stock'], //记录的金额应该是入库的加权单价
                                'bill_cost'=>$v['share_price'], //记录的金额应该是入库的采购成本
                                'balance'=>$balance, //记录的金额当前库存总额
                            ));
                        }
                    }
                    Db::name('purchase_enter_goods')->where(array('goods_id'=>1,'purchase_enter_id'=>$ids))->update(array('is_share' => 1));
                    $this->model->save(array('is_share' => 1), array('id' => $ids));
                    Db::commit();
                    return  array(
                        'code'=>1,
                        'msg'=>'分摊成功',
                    );
                }catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }else{
                Db::startTrans();
                try {
                    foreach ($gdata as $v) {
                        $EnterGoods = new EnterGoods;
                        $row = $EnterGoods->where(array('id' => $v['goods_id']))->find();
                        if ($row) {
                            $costprice = $row['unit_price'];
                            $EnterGoods = new EnterGoods;
                            $EnterGoods->save(array(
                                'share_price' => 0,
                                'cost_price' => $costprice,
                                'is_share' => 1,
                            ), array('id' => $row['id']));
                        }else{
                            throw new Exception('商品信息不存在');
                        }
                    }
                    $this->model->save(array('is_share' => 1), array('id' => $ids));
                    Db::commit();
                    return  array(
                        'code'=>1,
                        'msg'=>'分摊成功',
                    );
                }catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }



        }

        $list = Db::name('purchase_enter_goods')
            ->field('pg.id,g.number,title,place_origin,specs,goods_num,unit_price,tax,remark,pg.goods_id,storehouse_id,unit,ht_price')
            ->alias('pg')
            ->where(array('purchase_enter_id'=>$ids))
            ->join('goods g','pg.goods_id = g.id')
            ->select();
        $com_fare = 0;
        foreach ($list as $k=>$v){
            if($v['goods_id'] == 1){
                $com_fare = $com_fare+$v['unit_price']*$v['goods_num'];
                unset($list[$k]);
                continue;
            }
            $list[$k]['buy_price'] = round($v['goods_num']*($v['ht_price']/((100+$v['tax'])/100)),2);
            $list[$k]['tax_all'] = round(($v['ht_price']/($v['tax']+100))*$v['tax']*$v['goods_num'],2);
        }
        $com_fare+=$row['allfare'];
        $this->assign('com_fare',$com_fare);
        $this->assign('row',$row);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    public function export(){
        if ($this->request->isAjax()) {
            exit;
        }
        $this->assign('statuslist',$this->model->enter_status());
        return $this->view->fetch();
    }
    public function exportExcel(){

        $is_factory = input('is_factory/d',0);
        $start_time = input('start_time');
        $end_time = input('end_time');
        $status = input('status/d',0);
        $supplier_id = input('supplier_id/d',0);
        $storehouse_id = input('storehouse_id/d',0);
        $where=[];
        $ewhere['pg.status'] = 2;
        $dwhere['source_type'] = 2;//差价单据条件
        $dwhere['status'] = 2;//差价单据条件
        if(empty($start_time)){
            $start_time = 0;
        }
        if(empty($end_time)){
            $end_time = time();
        }
//        if($status >0){
//            $where['e.status'] =$status;
//        }
        if($supplier_id >0){
            $ewhere['e.supplier_id'] =$supplier_id;
            $dwhere['supplier_id'] =$supplier_id;
        }
        if($storehouse_id >0){
            $ewhere['e.storehouse_id'] =$storehouse_id;
            $dwhere['storehouse_id'] =$storehouse_id;
        }


        $ewhere['pg.createtime'] =  array('between time',[$start_time,$end_time]);
//        $dwhere['createtime'] =  array('between time',[$start_time,$end_time]);
        if($status >0){
            $ewhere['status'] =$status;
        }
//        dump($ewhere);
//        dump($where);
//        exit;
//        $enter_ids = $this->model->field('id')->where($ewhere)->select();
//
//        if(empty($enter_ids)){
//           $this->error('无数据');
//        }
//        foreach ($enter_ids  as $v){
//            $ids[]=$v['id'];
//        }
//        $where['pg.purchase_enter_id'] = array('in',$ids);
//        $where['zax_purchase_enter.createtime'] = array('between',[$start_time,$end_time]);

        $rows = Db::name('purchase_enter_goods')
            ->field('pg.goods_id,e.id,o.createtime as otime,e.number,g.unit,g.specs,pg.unit_price,e.createtime,pg.goods_num,pg.tax,e.operator,h.name,s.nickname,g.title,pg.ht_price')
            ->alias('pg')
            ->join('purchase_enter e','pg.purchase_enter_id = e.id')
            ->join('goods g','pg.goods_id = g.id')
            ->join('purchase_order o','pg.purchase_order_id = o.id')
            ->join('supplier s','e.supplier_id = s.id')
            ->join('storehouse h','pg.storehouse_id = h.id')
            ->where($ewhere)
//            ->whereBetween( "e.createtime" , $start_time.",".$end_time )
            ->select();

        $drows = Db::name('disparity')
            ->alias('d')
            ->join('disparity_goods g','d.id = g.disparity_id')
            ->where($dwhere)
            ->select();

        if(!empty($drows)){
            foreach ($drows as $v){
                foreach ($rows as $key => $val){
                    if($v['source_id'] == $val['id'] && $val['goods_id'] == $v['goods_id']){
                        $rows[$key]['diff_num']= $v['diff_num'];
                        $rows[$key]['diff_price1']= $v['diff_price1'];
                        $rows[$key]['diff_price2']= $v['diff_price2'];
                        $rows[$key]['diff_tax']= $v['tax'];
                        $rows[$key]['diff_sfhj']= $v['sfhj'];
                        $rows[$key]['diff_actual_cost']= $v['actual_cost'];
                    }
                }
            }
        }

//        dump($is_factory);
        $newRows = [];
        if($is_factory == 1 ){
//            dump($where);
            $newRows = Db::name('factory_sales_goods')
                ->where($ewhere)
                ->field('e.id,pg.goods_id,e.createtime ,e.number,g.unit,g.specs,unit_price,goods_num,pg.unit_tax as tax,e.operator,s.nickname,g.title,unit_ht_price as ht_price,unit_allfare,allfare_type ')
                ->alias('pg')
                ->join('goods g','pg.goods_id = g.id')
                ->join('factory_sales e','pg.factory_sales_id = e.id')
                ->join('supplier s','e.supplier_id = s.id')
                ->select();
            $fare = [];
            foreach ($newRows as $v){
                if($v['unit_allfare'] >0 && $v['allfare_type'] == 1){
                    $fare[$v['id']] = $v;
                }
            }
            foreach ($fare as $k=> $v){
                $yrow = Db::name('goods')->where(array('id'=>1))->find();
                $data = $v;
                $data['goods_id'] = 1;
                $data['title'] = $yrow['title'];
                $data['unit'] = $yrow['unit'];
                $data['specs'] = $yrow['specs'];
                $data['unit_price'] = $v['unit_allfare'];
                $data['ht_price'] = $v['unit_allfare'];
                $data['tax'] = 0;
                $data['goods_num'] = 1;
                $newRows[] = $data;
            }

            $dwhere['source_type'] = 12;
            $fdrows = Db::name('disparity')
                ->alias('d')
                ->join('disparity_goods g','d.id = g.disparity_id')
                ->where($dwhere)
                ->select();
            if(!empty($fdrows)){
                foreach ($fdrows as $v){
                    foreach ($newRows as $key => $val){
                        if($v['source_id'] == $val['id'] && $val['goods_id'] == $v['goods_id']){
                            $newRows[$key]['diff_num']= $v['diff_num'];
                            $newRows[$key]['diff_price1']= $v['diff_price1'];
                            $newRows[$key]['diff_price2']= $v['diff_price2'];
                            $newRows[$key]['diff_tax']= $v['tax'];
                            $newRows[$key]['diff_sfhj']= $v['sfhj'];
                            $newRows[$key]['diff_actual_cost']= $v['actual_cost'];
                        }
                    }
                }
            }
        }
//        dump(count($newRows));
//        dump(count($rows));

        foreach ($newRows as $v){
            $datas = $v;
            $datas['type'] = 1;
            $datas['name'] = '';
            $rows[]= $datas;
        }
//        dump($rows);
//        exit;
//        ["otime"] => int(1596532720)
//        ["number"] => string(20) "JK-T-2020-08-04-0001"
//        ["unit"] => string(0) ""
//        ["specs"] => string(0) ""
//        ["unit_price"] => string(4) "2.00"
//        ["createtime"] => int(1596532861)
//        ["goods_num"] => int(1)
//        ["tax"] => string(4) "0.00"
//        ["operator"] => string(5) "Admin"
//        ["name"] => string(18) "杭州正品仓库"
//        ["nickname"] => string(54) "（汕头市潮南区司马浦）永信电器加工厂"
//        ["title"] => string(9) "铜闸阀"
//          dump($rows);
//          exit;
//        $Storehouse = new Storehouse;
//        $houses = $Storehouse->select();
//
//        dump($rows);
//        dump($where);
//        exit;



        $template_path = config('site.file_url').'/template/demo.xls';
        $spreadsheet = IOFactory::load($template_path);
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
//        $worksheet->setTitle('学生成绩表');
        //设置单元格内容
//        $worksheet->setCellValueByColumnAndRow(1, 1, '学生成绩表');
//        $worksheet->setCellValueByColumnAndRow(1, 2, '姓名');
//        $worksheet->setCellValueByColumnAndRow(2, 2, '语文');
//        $worksheet->setCellValueByColumnAndRow(3, 2, '数学');
//        $worksheet->setCellValueByColumnAndRow(4, 2, '外语');
//        $worksheet->setCellValueByColumnAndRow(5, 2, '总分');
        //合并单元格
//        $worksheet->mergeCells('A1:E1');
        if($supplier_id>0){
            $srow = Supplier::get($supplier_id);
            $worksheet->setCellValueByColumnAndRow(3, 2,$srow['nickname']);
        }

        $worksheet->setCellValueByColumnAndRow(8, 2,$start_time );
        $worksheet->setCellValueByColumnAndRow(8, 3, $end_time);
        $len = count($rows);
        for ($i=0; $i < $len; $i++) {
            $j = $i + 5;
            //从表格第3行开始
            $worksheet->setCellValueByColumnAndRow(1, $j, $i+1);
//            $worksheet->setCellValueByColumnAndRow(2, $j, isset($rows[$i]['otime'])?date('Y-m-d',$rows[$i]['otime']):'');
            $worksheet->setCellValueByColumnAndRow(2, $j, date('Y-m-d',$rows[$i]['createtime']));
            $worksheet->setCellValueByColumnAndRow(3, $j, $rows[$i]['number']);
            if(isset($rows[$i]['type'])){
                $worksheet->setCellValueByColumnAndRow(4, $j, '厂家直发单');
            }else{
                $worksheet->setCellValueByColumnAndRow(4, $j, '采购入库单');
            }

            $worksheet->setCellValueByColumnAndRow(5, $j, $rows[$i]['nickname']);
            $worksheet->setCellValueByColumnAndRow(6, $j, $rows[$i]['operator']);
            $worksheet->setCellValueByColumnAndRow(7, $j, $rows[$i]['name']);
            $worksheet->setCellValueByColumnAndRow(8, $j, $rows[$i]['title']);

            if(isset($rows[$i]['diff_num'])){
                $worksheet->getStyle('L'.$j)->getFont()->getColor()->setRGB('#d4173a');
                $worksheet->setCellValueByColumnAndRow(10, $j, $rows[$i]['goods_num'].'/'.$rows[$i]['diff_num']);
            }else{
                $worksheet->setCellValueByColumnAndRow(10, $j, $rows[$i]['goods_num']);
            }



            $worksheet->setCellValueByColumnAndRow(9, $j, $rows[$i]['specs']);
            if(isset($rows[$i]['diff_price1'])){
                $worksheet->getStyle('K'.$j)->getFont()->getColor()->setRGB('#d4173a');
                $worksheet->setCellValueByColumnAndRow(11, $j, $rows[$i]['unit_price'].'/'.$rows[$i]['diff_price1']);
            }else{
                $worksheet->setCellValueByColumnAndRow(11, $j, $rows[$i]['unit_price']);
            }

            if(isset($rows[$i]['diff_tax'])){
                $worksheet->getStyle('L'.$j)->getFont()->getColor()->setRGB('#d4173a');
                $worksheet->setCellValueByColumnAndRow(12, $j, $rows[$i]['tax'].'/'.$rows[$i]['diff_tax']);
            }else{
                $worksheet->setCellValueByColumnAndRow(12, $j, $rows[$i]['tax']);
            }

            if(isset($rows[$i]['diff_price2'])){
                $worksheet->getStyle('M'.$j)->getFont()->getColor()->setRGB('#d4173a');
                $worksheet->setCellValueByColumnAndRow(13, $j, $rows[$i]['ht_price'].'/'.$rows[$i]['diff_price2']);
            }else{
                $worksheet->setCellValueByColumnAndRow(13, $j, $rows[$i]['ht_price']);
            }
            $worksheet->setCellValueByColumnAndRow(14, $j, $rows[$i]['ht_price']*$rows[$i]['goods_num']);
            if(isset($rows[$i]['diff_sfhj'])){
                $worksheet->setCellValueByColumnAndRow(15, $j, $rows[$i]['diff_sfhj']);
            }else{
                $worksheet->setCellValueByColumnAndRow(15, $j, 0);
            }
            if(isset($rows[$i]['diff_sfhj'])){
                $worksheet->setCellValueByColumnAndRow(16, $j,$rows[$i]['ht_price']*$rows[$i]['goods_num']+$rows[$i]['diff_sfhj']);
            }else{
                $worksheet->setCellValueByColumnAndRow(16, $j, $rows[$i]['ht_price']*$rows[$i]['goods_num']);
            }
        }

        $filename = '入库单.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');






    }
    public function cancelbill($ids = null){
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        if(!$this->request->isAjax()){
            $this->error('非法操作');
        }
        $row = $this->model->find($ids);

        if($row['status'] !=2){
            $this->error('状态异常');
        }
        if($row['is_share'] == 1 && $row['allfare'] >0){
            $this->error('请先处理分摊单据');
        }
        $analysis = '';
        if($row['allfare'] >0){
            $analysis = Db::name('analysis')->where(array(
                'source'=>2,
                'source_id' => $row['id'],
                'storehouse_id' => $row['storehouse_id'],
            ))->find();
            //只有财务数据在待处理的时候 才能处理
            if($analysis['status'] != 1){
                $this->error('财务状态异常,请处理');
            }
        }

        //有费用单的情况
        $costrow = Db::name('cost')->where(array('source_type'=>2,'source_id'=>$ids))->find();
        if(!empty($costrow)){
            if($costrow['status'] <3){
                $this->error('还有待处理的费用单');
            }
        }

        Db::startTrans();
        try {
            $enterGoods = new EnterGoods();
            $list = $enterGoods->where(array('purchase_enter_id'=>$ids))->select();

            //修改所有商品状态
            $egoods = new EnterGoods();
            $egoods->save(array('status'=>0),array('purchase_enter_id'=>$ids));
            //修改单据状态
            $this->model->save(array('status'=>4),array('id'=>$ids));

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                foreach ($list as $v) {
                    $hgood = Db::name('goods_house_stock')->where(array('goods_id' => $v['goods_id'], 'storehouse_id' => $row['storehouse_id']))->find();
                    if ($hgood['stock'] == 0) {
                        throw new Exception('库存为0');
                    }

                    if ($hgood['stock'] == $v['goods_num']) {
                        $balance = 0;
                    } else {
                        $balance = $hgood['balance'] - handle_price($v['ht_price'], $v['tax']) * $v['goods_num'];
                    }

                    Db::name('goods_stock_log')->insert(array(
                        'goods_id' => $v['goods_id'],
                        'createtime' => time(),
                        'number' => $row['number'],
                        'type' => '采购入库单',
                        'source' => 2,
                        'type_id' => $ids,
//                    'enter_num'=>$v['goods_num'],
                        'out_num' => $v['goods_num'],
                        'before_num' => $hgood['stock'],
                        'now_num' => $hgood['stock'] - $v['goods_num'],
                        'storehouse_id' => $row['storehouse_id'],
                        'controller' => 'purchase/enter',
                        'admin_id' => session('admin')['id'],
                        'group_id' => $group['group_id'],
                        'company' => $group['name'],
                        'operator' => session('admin')['nickname'],
                        'final_cost' => handle_price($v['ht_price'], $v['tax']), //记录的金额应该是入库的加权单价
                        'bill_cost' => handle_price($v['ht_price'], $v['tax']) * $v['goods_num'], //记录的金额应该是入库的采购成本
                        'balance' => $balance, //记录的金额当前库存总额
                        'is_cancel' => 1,
                    ));
                    $house = new GoodsHouseStock();
                    $res = $house->reducestock($v['goods_id'], $row['storehouse_id'], $v['goods_num'], handle_price($v['ht_price'], $v['tax']));
                    if (!$res) {
                        throw new Exception('库存计算错误');
                    }

                }
            //已入库数量
            $egoods = new EnterGoods();
            $rnum = $egoods->where(array('purchase_order_id'=>$row['purchase_order_id'],'status'=>array('>',0)))->sum('goods_num');
//            $ogoods = new Goods();
//            $gnum = $ogoods->where(array('purchase_order_id'=>$row['purchase_order_id'],'status'=>array('>',0)))->sum('goods_num');

            if($rnum >0){
                Db::name('purchase_order')->where(array('id'=>$row['purchase_order_id']))->update(array('status'=>3));
            }else{
                Db::name('purchase_order')->where(array('id'=>$row['purchase_order_id']))->update(array('status'=>2));
            }

            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 2,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'purchase/enter',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));

            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'purchase/enter',
                'source_id'=>$ids,
                'source'=>2,
                'remark'=>'采购入库单',
                'number'=>isset($row['number'])?$row['number']:'',
            ));
            if($analysis){
                //中止财务记录
                $ress = Db::name('analysis')->where(array(
                    'id' => $analysis['id']
                ))->update(array('status' => 4));
                if (!$ress) {
                    throw new Exception('数据异常');
                }
            }



            Db::commit();
            return array(
                'code' => 1,
                'msg' => '成功'
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }


    }
    public function printing($ids){
        $row = $this->model->find($ids);
        $list = Db::name('purchase_enter_goods')
            ->field('pg.id,g.number,title,place_origin,specs,goods_num,unit_price,tax,remark,pg.goods_id,storehouse_id,unit,ht_price')
            ->alias('pg')
            ->where(array('purchase_enter_id'=>$ids))
            ->join('goods g','pg.goods_id = g.id')
            ->select();
       $goods_price = 0;
        foreach ($list as  $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
            $goods_price = bcadd($goods_price,bcmul($v['goods_num'],$v['ht_price'],4),4);
        }
        $Voucher = new Voucher;
        $vrow = $Voucher->where(array('source_id'=>$ids,'type'=>2))->find();


        $hrow = Db::name('storehouse')->where(array('id'=>$row['storehouse_id']))->find();
        $srow = Db::name('supplier')->where(array('id'=>$row['supplier_id']))->find();
        $this->assign('hrow',$hrow);
        $this->assign('srow',$srow);
        $this->assign('vrow',$vrow);
        $this->assign('goods_price',$goods_price);
        $this->assign('row',$row);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
}
